package com.gitee.wsl.net.server.role.login

import com.gitee.wsl.net.server.role.admin.AdminsService
import com.gitee.wsl.net.server.role.admin.SessionService
import com.gitee.wsl.text.regex.sample.isEmail
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.requestvalidation.RequestValidation
import io.ktor.server.plugins.requestvalidation.RequestValidationException
import io.ktor.server.plugins.requestvalidation.ValidationResult
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.response.respond
import io.ktor.server.routing.routing
import kotlinx.serialization.Serializable

@Serializable
internal data class Request(
    val email: String? = null,

    val password: String? = null
)

fun Application.loginModule(sessionService: SessionService,
                            adminsService: AdminsService
) {
    //install(RequestValidation)
    // ...
    install(RequestValidation) {
        validate<Request> { bodyText ->
            if (bodyText.email?.isEmail() == false)
                ValidationResult.Invalid("Body text should start with 'Hello'")
            else ValidationResult.Valid
        }
    }

    install(StatusPages) {
        exception<RequestValidationException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, cause.reasons.joinToString())
        }
    }

    routing {
        login(sessionService, adminsService)
        logout()
    }

}